import string
from django.core.mail import send_mail
from rest_framework.views import APIView
from rest_framework.response import Response
from django import forms
from app01 import models
from django.shortcuts import render
from django.core.validators import RegexValidator
import random
from django.http.response import JsonResponse
# Create your views here.

class RegisterView(forms.ModelForm):
    mobel_phone = forms.CharField(label='手机号', widget=forms.TextInput(),validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误')])
    password = forms.CharField(label="密码", widget=forms.PasswordInput())
    confrim_password = forms.CharField(label="确认密码", widget=forms.PasswordInput())
    code = forms.CharField(label='验证码')

    class Meta:
        model = models.UserInfo
        fields = ['username','mobel_phone','password', 'confrim_password','email',  'code']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = "请输入" + field.label

def send_email_captcha(request):
    email = request.GET.get('email')
    if not email:
        return JsonResponse({'code':1000,'message':"必须传递邮箱"})
    captcha = "".join(random.sample(string.digits,4))
    send_mail("北冥的验证码",message=f"您的验证码是：{captcha}",recipient_list=[email],from_email=None)
    return JsonResponse({"code":200,"message":"发送成功！"})



class register(APIView):
    def get(self, request):
        form = RegisterView()
        return render(request, 'register.html', {'form': form})

    def post(self, request):
        pass



